221.Maximal Square

Maximal Square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

Example:

1
2
3
4
5
6
7
8
Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

解法1:单调栈

解法详见程序员代码面试指南:求最大子矩阵的大小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
if(matrix.empty() || matrix[0].empty()){
return 0;
}
int maxArea = 0;
int row = matrix.size(); // 1
int col = matrix[0].size(); // 1
vector<int> height(col, 0);
for(int i=0;i<row;++i){

for(int j=0;j<col;++j){
height[j] = (matrix[i][j] == '0') ? 0 : height[j] + 1;
}
auto res = getLessThan(height);
for(int j=0;j<col;++j){
int w = res[j][1] - res[j][0] - 1;
int l = min(w, height[j]);
maxArea = max(maxArea, l * l);
}
}
return maxArea;
}
vector<vector<int>> getLessThan(vector<int>& nums){
vector<vector<int>> res(nums.size(), vector<int>(2, -1));
stack<int> s1;
for(int i=0;i<nums.size();++i){
int r = i;
while(!s1.empty() && nums[s1.top()] >= nums[i]){
int index = s1.top();
s1.pop();
int l = s1.empty() ? -1 : s1.top();
res[index][0] = l;
res[index][1] = r;
}
s1.push(i);
}
int r = nums.size();
while(!s1.empty()){
int index = s1.top();
s1.pop();
int l = s1.empty() ? -1 : s1.top();
res[index][0] = l;
res[index][1] = r;
}
return res;
}
};

解法2:动态规划